package com.kfm.servlet;

import com.kfm.entity.User;
import com.kfm.service.UserService;
import com.kfm.util.Contains;
import com.kfm.util.UUIDUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.time.LocalDate;

@WebServlet("/user/edit")
@MultipartConfig
public class UserEditServlet extends HttpServlet {

    private UserService service = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String role = req.getParameter("role");
        Part pic = req.getPart("pic");
        String id = req.getParameter("id");

        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setRole(Integer.parseInt(role));

        if (pic.getSize() > 0){ // 如果修改了头像
             // 输出流
            String date = LocalDate.now().toString().replace("-", "");// 当前日期 20221017
            File directory = new File(Contains.FILE_PATH, date);
            if (!directory.exists()){
                directory.mkdirs(); // 文件夹不存在则创建
            }
            // 获取文件的后缀
            int index = pic.getSubmittedFileName().lastIndexOf(".");
            String suff = pic.getSubmittedFileName().substring(index);
            String saveFileName = UUIDUtil.uuid32() + suff;
            // 保存的文件
            String saveFilePath = directory + File.separator + saveFileName;
            // 保存文件的操作 TODO(删除原头像资源)
            pic.write(saveFilePath);

            user.setPic(URLEncoder.encode(date +File.separator + saveFileName, Charset.defaultCharset()));
        }

        int row = service.updateUser(user);

        if (row > 0){
            // 修改成功\
//            Object attribute = req.getSession().getAttribute(Contains.LOGIN_USER);
//            if (attribute instanceof User user1){
//                user1.setName(name);
//            }
            req.getSession().removeAttribute(Contains.LOGIN_USER); // 删除原来的信息
            User user1 = service.findById(id);
            req.getSession().setAttribute(Contains.LOGIN_USER, user1);
            resp.sendRedirect("/page?n=info");
        } else{
            req.setAttribute("msg", "修改失败");
            req.getRequestDispatcher("/WEB-INF/info.jsp").forward(req, resp);
        }
    }
}
